package com.woniuxy.main.pay.handler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.woniuxy.main.mycenter_ty.pojo.User_Ty;
import com.woniuxy.main.mycenter_ty.service.MyCenterService;
import com.woniuxy.main.pay.pojo.Order;
import com.woniuxy.main.pay.pojo.OrderComment;
import com.woniuxy.main.pay.pojo.OrderTypeCount;
import com.woniuxy.main.pay.service.OrderService;
import com.woniuxy.main.pay.service.PayService;

@Controller
public class OrderHandler {
	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;
	@Autowired
	private MyCenterService personCenterservice;
	
//	private Integer userid=0;
	private Integer newCurrentPage=1;
	
	
	/**
	 * 查询所有订单
	 * @param userId 
	 * @param orderShowState
	 * @return
	 */
	@RequestMapping("/allOrder")
	@ResponseBody
    public ModelAndView allOrder(){
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userId=user.getUser_id();   // 当前用户的id
		Integer userRole=user.getRole_id();
		
		Integer orderShowState=0;
		System.out.println("当前用户的id"+userId);
		Integer pageSize=3;Integer currentPage=1;
		List<Order> orderShow=orderService.allOrderService(userId,currentPage,pageSize,orderShowState,userRole);
		OrderTypeCount otc=orderService.orderTC(userId,userRole);
		newCurrentPage=1;
		
		ModelAndView ma=new ModelAndView();
		ma.addObject("userId", userId);
		ma.addObject("OrderTypeCount", otc);
		ma.addObject("orderShow", orderShow);
		ma.addObject("role", userRole);
		ma.setViewName("/orders.html");
		return ma;
    }
	
	List<Order> orderShow=null;
	OrderTypeCount otc=null;
	Integer newOrderShowState=0;
	
	
	
	@RequestMapping("/orderShow")
	@ResponseBody
    public Map orderShow(Integer orderShowState){
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userId=user.getUser_id();   // 当前用户的id
		Integer userRole=user.getRole_id();
		
		Map<String, Object> map=new HashMap<String, Object>();
		Integer pageSize=3;
		Integer currentPage=1;
//		userid=userId;
		newOrderShowState=orderShowState;
		List<Order> orderShowTemp=orderService.allOrderService(userId,currentPage,pageSize,orderShowState,userRole);
		Integer roletemp=orderService.searchUserRole(userId);
		OrderTypeCount otcTemp=orderService.orderTC(userId,userRole);
		
//		role=roletemp;
		otc=otcTemp;
		orderShow=orderShowTemp;
		return map;
    }
	
	@RequestMapping("/toOrderShow")
	@ResponseBody
	public ModelAndView toOrderShow(){
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userRole=user.getRole_id();
		Integer userId=user.getUser_id();   // 当前用户的id
		
		ModelAndView ma=new ModelAndView();
		newCurrentPage=1;
		ma.addObject("userId", userId);
		ma.addObject("newOrderShowState", newOrderShowState);
		ma.addObject("OrderTypeCount", otc);
		ma.addObject("orderShow", orderShow);
		ma.addObject("role", userRole);
		ma.setViewName("/orders.html");
		return ma;
	}
	
	//下拉翻页
	@RequestMapping("/xiala")
	@ResponseBody
    public Map<String, Object> xiala(Integer orderShowState){
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userId=user.getUser_id();   // 当前用户的id
		Integer userRole=user.getRole_id();
		if(orderShowState==null){
			orderShowState=0;
		}
		Map<String, Object> map=new HashMap<String, Object>();
		Integer pageSize=3;
//		userid=userId;
		Integer currentPage=1+newCurrentPage;
//		System.out.println("打桩 当前页数"+currentPage+":"+userId+":"+orderShowState+":"+pageSize);
		
		List<Order> orderShow=orderService.allOrderService(userId,currentPage,pageSize,orderShowState,userRole);
		map.put("role", 1);
		map.put("orderShow", orderShow);
		newCurrentPage+=1;
		return map;
    }
	
//	String comment=null;
	Order orderDetail=null;
	@RequestMapping("/detail")
	@ResponseBody
	public Map detail(Integer orderId){
		Order orderDetailtemp=orderService.detailService(orderId);
//		String comments=orderService.selectComment(orderId);
//		comment=comments;
		Map<String, Object> map=new HashMap<String, Object>();
		orderDetail=orderDetailtemp;
		return map;
	}
	
	@RequestMapping("/toOrder")
	@ResponseBody
	public ModelAndView toOrder(){
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userId=user.getUser_id();   // 当前用户的id
		Integer userRole=user.getRole_id();
		
		ModelAndView mv =new ModelAndView();
		mv.addObject("role", userRole);
		mv.addObject("userId", userId);
//		mv.addObject("comment", comment);
		mv.addObject("orderDetail", orderDetail);
		mv.setViewName("order");
//		System.out.println("打桩2222:");
		return mv;
	}
	
	
	private String results;
	@RequestMapping("/addOrder")
	@ResponseBody
	public Map addOrder(Integer money,Integer coachId,Integer venueId,String courseName,String courseTime,Integer courseDuration){
		Map<String, Object> map=new HashMap<String, Object>();
		String phone = (String) SecurityUtils.getSubject().getPrincipal();
		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
		Integer userId=user.getUser_id();   // 当前用户的id
		System.out.println("当前用户ID"+userId);
		Integer studentId=orderService.searchStudentId(userId);
		System.out.println("学生ID：：：：："+studentId);
		
		String courseTimeN=dispose(courseTime);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String orderNumber="YOGA"+sdf.format(new Date());
		System.out.println(orderNumber);
		List<Order> orderAll=orderService.searchOrder(userId,0);
		List<Order> orderCoachAll=orderService.searchCoachOrder(coachId);
		Integer balance=payService.searchBalance(userId);
		String result="预定失败!!!情况不明";
		if(balance>=money){
			result=disposeTiem(orderAll,courseTimeN,courseDuration);
			if(result.indexOf("成功")>=0){
				result=disposeTiem(orderCoachAll,courseTimeN,courseDuration);
				if (result.indexOf("成功")>=0) {
					Order addOrder=new Order();
					addOrder.setOrderNumber(orderNumber);//订单号
					addOrder.setOrderMoney(money);//金额
					addOrder.setCoachId(coachId);//教练id
					addOrder.setVenueId(venueId);//场馆id
					addOrder.setStudentId(studentId);//用户id
					addOrder.setUserId(studentId);//用户id2
					addOrder.setCourseTime(courseTimeN);//上课时间
					addOrder.setCourseDuration(courseDuration);//学习时长
					addOrder.setCourseName(courseName);//课程名称
					orderService.addOrder(addOrder);
					orderService.minus(userId,money);
				}else{
					result="教练这个时段已经有预约!你们不会聊下天再下单吗?";
				}
			}
		}else if (money>balance) {
			result="预定失败!!!余额不足";
		}
		results=result;
		System.out.println(result);
		map.put("addOrederResult", result);
		return map;
	}
	
	
	private String dispose(String courseTime) {
		String a=courseTime;
		String b=a.substring(0,2);
		String c=a.substring(3, 5);
		String d=a.substring(6, 10);
		String e=a.substring(10);
		String f=d+"-"+c+"-"+b+e;
		return f;
	}

	private String disposeTiem(List<Order> orderAll, String a, Integer c) {
		String result="预定成功!快去愉快的学习吧";
		String reserveDate=a.substring(0, 10);//年月日
		int a2=Integer.parseInt(a.substring(11, 13));//小时
		int a3=Integer.parseInt(a.substring(14, 16));//分钟
		int a4=Integer.parseInt(a.substring(17, 19));//秒
		int secondSum=(a2*60*60)+(a3*60)+a4;//预定开始时间
		int overSecondSum=(a2*60*60)+(a3*60)+(c*60)+a4;//预定结束时间
		for (Order order : orderAll) {
			String oldTime=order.getCourseTime();//数据库时间
			int oldCourseDuration=order.getCourseDuration();//数据库学习时间
			String oldReserveDate=oldTime.substring(0, 10);//数据库时间的年月日
			int olda2=Integer.parseInt(oldTime.substring(11, 13));//小时
			int olda3=Integer.parseInt(oldTime.substring(14, 16));//分钟
			int olda4=Integer.parseInt(oldTime.substring(17, 19));//秒
			int oldSecondSum=(olda2*60*60)+(olda3*60)+olda4;//预定开始时间
			int oldOverSecondSum=(olda2*60*60)+(olda3*60)+(oldCourseDuration*60)+olda4;//预定结束时间
			if(oldReserveDate.equals(reserveDate)){
				if(secondSum>=oldSecondSum && overSecondSum<=oldOverSecondSum){
					result="预定失败!该时间段已预定别的课程,订单号为:"+order.getOrderId()+"请重新选择";
				}
				if(overSecondSum>=oldSecondSum && overSecondSum<=oldOverSecondSum){
					result="预定失败!该时间段已预定别的课程,订单号为:"+order.getOrderId()+"请重新选择";
				}
			}
		}
		return result;
	}

//	@RequestMapping("/toAddOrder")
//	public ModelAndView toAddOrder(){
//		String phone = (String) SecurityUtils.getSubject().getPrincipal();
//		User_Ty user = personCenterservice.queryAllInfoByPhone(phone); // 个人资料
//		Integer userId=user.getUser_id();   // 当前用户的id
//		Integer userRole=user.getRole_id();
//		
//		ModelAndView mv =new ModelAndView();
//		mv.addObject("addOrederResult", results);
//		mv.addObject("role", userRole);
//		mv.addObject("userId", userId);
//		mv.setViewName("allOrder");
//		return mv;
//	}
	
	@RequestMapping("/updataOrderState")
	@ResponseBody
	public Map updataOrderState(Integer orderId,Integer stateId){
		Date orderComplete=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String courseTimeNew=sdf.format(orderComplete);
		
		orderService.updateStateTime(orderId,stateId,courseTimeNew);
		Map<String, Object> map=new HashMap<String, Object>();
		String result="愉快的学习开始咯";
		map.put("addOrederResult", result);
		return map;
	}
	@RequestMapping("/updataOrderState2")
	@ResponseBody
	public Map updataOrderState2(Integer orderId,Integer stateId){
		Date orderComplete=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String courseTimeNew=sdf.format(orderComplete);
		Order upOrder=new Order();
		upOrder.setOrderId(orderId);
		upOrder.setOrderState(stateId);
		upOrder.setOrderComplete(courseTimeNew);
		String result=orderService.coachTime(orderId);
		orderService.updateState2(upOrder);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("addOrederResult", result);
		return map;
	}
	
	@RequestMapping("/updataOrderState3")
	@ResponseBody
	public Map updataOrderState3(Integer orderId,Integer stateId){
		String result=orderService.upOrderState3(orderId,stateId);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("addOrederResult", result);
		return map;
	}
	
	@RequestMapping("/updataOrderState4")
	@ResponseBody
	public Map updataOrderState4(String comment,Integer orderId,Integer grade){
		OrderComment comments=new OrderComment();
		comments.setOrder_id(orderId);
		comments.setOc_student_detail(comment);
		comments.setOc_score(grade);
		orderService.addComment(comments);
		Map<String, Object> map=new HashMap<String, Object>();
		return map;
	}
	
	@RequestMapping("/cancel")
	@ResponseBody
	public Map cancel(Integer stateId,Integer orderId){
		String result=orderService.cancel(orderId,stateId);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("addOrederResult", result);
		return map;
	}
	
}
